package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.constans.MqConstant;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.model.to.order.OrderCreateTo;
import com.atguigu.gmall.model.to.ware.WareOrderTo;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/9/15 0:31
 */
@Slf4j
@Component
public class OrderMqListener {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    // 监听死信队列, 关闭订单
    @RabbitListener(queues = {MqConstant.ORDER_DEAD_QUEUE})
    public void CloseOrder(Message message, Channel channel){
        byte[] messageBody = message.getBody();
        OrderCreateTo orderCreateTo = JsonUtil.jsonToObject(new String(messageBody), new TypeReference<OrderCreateTo>() {
        });
        try {
            orderInfoService.closeOrder(orderCreateTo);
            log.info("自动关闭订单成功：{}", orderCreateTo);
        } catch (Exception e) {
            log.error("关闭订单失败：{},消息内容：{}", e.getMessage(),orderCreateTo);
        }

        // 手动ack确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("手动ack确认消息失败：{}", e.getMessage());
        }
    }

    //监听状态为paid的队列，更新订单状态为已支付
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConstant.ORDER_EVENT_EXCHANGE,type = "topic"),
            value = @Queue(value = MqConstant.ORDER_STATUS_PAID_QUEUE,
                    durable = "true",exclusive = "false",autoDelete = "false",declare = "true"),
            key = {MqConstant.ORDER_STATUS_PAID_ROUTING_KEY}
    ))
    public void updateOrderStatusToPaid(Message message, Channel channel){
        byte[] body = message.getBody();
        String outTradeNo = new String(body);
        try {
            //监听到消息后，更新订单状态为已支付
            orderInfoService.updateOrderStatusToPaid(outTradeNo);
            log.info("监听paid队列,更新订单状态为已支付成功：{}", outTradeNo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("更新订单状态为已支付失败：{},消息内容：{}", e.getMessage(), outTradeNo);
        }
        try {
            //发送消息给库存系统，通知减库存
            WareOrderTo wareOrderTo = orderInfoService.prepareWareOrderTo(outTradeNo);
            String str = JsonUtil.toStr(wareOrderTo);
            rabbitTemplate.convertAndSend(MqConstant.WARE_EVENT_EXCHANGE,MqConstant.WARE_STOCK_ROUTING_KEY,str);
            log.info("发送减库存消息成功：{}", wareOrderTo);
        }catch (Exception e){
            log.error("发送减库存消息失败：{},消息内容：{}", e.getMessage(), outTradeNo);
        }

    }
}
